import _thread
import json
from wsgiref.simple_server import make_server
#导入simple_server模块

#视图函数
import DbBase
import Fun
import Log
import devices_serial


def responseApiOk(data):
    res = {'status':'200','data':data,'message':'成功'}
    return json.dumps(res).encode('utf-8')
def responseApiError(text):
    res = {'status':'500','data':None,'message':text}
    return json.dumps(res).encode('utf-8')
def sendCmd(param):
    cmd = json.loads(param)
    resultList =  DbBase.getDataByName(cmd['name'])
    if len(resultList)==0:
        return responseApiError('未找到设备')
    Log.serialLog('连接设备:' + resultList[0][1]+resultList[0][2])
    Log.serialLog('串口:' + resultList[0][3]+'，波特率:'+resultList[0][4])
    Log.serialLog('发送命令:'+cmd['cmd'])
    res = devices_serial.oneSendCmd(resultList[0][3],resultList[0][4],cmd['cmd'])
    Log.serialLog('收到设备返回:' + res)
    return responseApiOk(res)

def routes():    # 配置路由
    route_pattern = [
        ("/sendCmd", sendCmd),
    ]
    return route_pattern

def app(environ, start_response):   # 定义应用
    status = '200 OK'
    # response_headers  中添加请求头部 ，解决跨域问题application/json;charset=UTF-8
    response_headers = [("Content-Type", "application/json;charset=UTF-8"),
                        ('Access-Control-Allow-Origin', '*'),
                        ('Access-Control-Allow-Methods', '*'),
                        ('Access-Control-Allow-Credentials', 'true'),
                        ('Access-Control-Allow-Headers', '*'),
                        ]  # json
    start_response(status, response_headers)
    method=environ.get('REQUEST_METHOD')
    path = environ.get('PATH_INFO')
    ip = environ.get('REMOTE_ADDR')
    if method == 'OPTIONS':
        return ["握手".encode('utf-8'),]
    Log.httpLog('收到请求：' + method + '  '+path+'  '+ip)



    func = None
    for item in routes():
        if environ['PATH_INFO'] == item[0]:
            func = item[1]
    if func:
        try:
            request_body_size = int(environ.get('CONTENT_LENGTH', 0))
        except (ValueError):
            request_body_size = 0
        request_body = environ['wsgi.input'].read(request_body_size)
        d = str(request_body, encoding="utf-8")
        Log.httpLog('请求参数：' + d)
        return [func(d)]
    return [b"<h1>page is not exist</h1>"]


serialServer = None

def startHttpServer(port):
    Log.httpLog('启动http服务器监听端口：'+port)
    _thread.start_new_thread(httpServerThread,(port,))
    Log.httpLog('启动http服务器成功')

def stopHttpServer():
    global serialServer
    if serialServer != None:
        try:
            serialServer.server_close()
        except Exception as e:
            print(e)
    serialServer = None
    Log.httpLog('关闭http服务器成功')

def httpServerThread(port):
    global serialServer
    if serialServer == None:
        serialServer = make_server("", int(port), app)
        serialServer.serve_forever()